# 实现文件的上传---头像上传
import os.path

from flask import blueprints, render_template, request, redirect, url_for, flash, Blueprint,current_app
from flask_login import login_required,current_user
from app import db
from werkzeug.utils import secure_filename

bp=Blueprint('profile', __name__,url_prefix='/profile')

# 检查文件后缀
def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in {'png', 'jpg', 'jpeg', 'gif'}

@bp.route('/avatar',methods=['GET','POST'])
@login_required
def upload_avatar():
    if request.method == 'POST':
        file=request.files['avatar']
        if file and allowed_file(file.filename):
            # 对文件名进行安全性校验
            filename= secure_filename(file.filename)
            # static/uploads/filename
            avatar_path = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)
            os.makedirs(current_app.config['UPLOAD_FOLDER'], exist_ok=True)
            file.save(avatar_path)

            # 把图片路径存储到user表的avatar字段中
            current_user.avatar = f'/static/uploads/avatars/{filename}'
            db.session.commit()
            flash('文件上传成功')
            return redirect(url_for('user_center.user_center'))
        else:
            flash('请上传合法的图片格式')

    return render_template('upload_avatar.html')

# http://localhost:5000/profile/avatar
# @bp.route('/avatar',methods=['GET','POST'])
# @login_required
# def upload_avatar():
#     if request.method == 'POST':
#         file=request.files['avatar']
#         if file:
#             # 1--tx.png
#             filename=f"{current_user.id}-{file.filename}"
#             filepath=os.path.join('static/uploads',filename)
#             # 保存文件到服务器的某个路径
#             file.save(filepath)
#             # 把图片路径存储到user表的avatar字段中
#             current_user.avatar=filepath
#             db.session.commit()
#             flash('上传成功')
#             return redirect(url_for('index.index'))
#
#     return render_template('upload_avatar.html')